<template>
  <div class="easy-table-container">
    <div class="table-tools" v-if="tools">
      <slot></slot>
    </div>
    <div class="table-wrapper">
      <el-table
        ref="table"
        v-loading="tableLoading"
        :highlight-current-row="highlightCurrentRow"
        :data="pageTableData"
        :height="tableHeight"
        :max-height="maxHeight"
        :border="border"
        :show-summary="showSummary"
        :sum-text="sumText"
        :summary-method="getSummaries"
        :need-summary-index="needSummaryIndex"
        :cell-style="cellStyle"
        empty-text="暂无数据"
        @row-click="rowClickHandler"
        @current-change="currentChangeHandler"
        @select="selectHandler"
        @select-all="selectAllHandler"
        :header-cell-style="headerStyle"
        :stripe="stripe"
        :span-method="spanMethod"
        @selection-change="selectChange"
        row-key="id"
      >
        <el-table-column v-if="selection" type="selection" :reserve-selection="reserveSelection" width="50" />
        <el-table-column
          v-if="showIndex"
          type="index"
          :label="indexOptions.label || '#'"
          :width="indexOptions.width || 50"
          :align="indexOptions.align"
          :fixed="indexOptions.fixed"
          :index="getIndex"
        />
        <el-table-column
          v-for="(column, index) in columns"
          :sortable="column.sortable || false"
          :key="column.name"
          :prop="column.name"
          :label="column.title"
          :fixed="column.fixed"
          :width="column.width"
          :min-width="column.minWidth"
          :show-overflow-tooltip="column.showOverflowTooltip"
          :align="column.align || align"
          :header-align="column.headerAlign || headerAlign"
        >
          <template #default="scope">
            <template v-if="column.type==='operate'">
              <template v-for="button in column.buttons" :key="button.name">
                <el-button
                  v-if="button.show ? button.show(scope.row) : true"
                  @click="button.click(scope.$index, scope.row)"
                  :type="button.buttonType || 'primary'"
                  link
                  :size="button.size ? button.size : 'small'"
                  :style="{color: button.color || ''}"
                  :disabled="typeof button.disabled === 'function' ? button.disabled(scope.row, scope.column) : button.disabled"
                >
                  {{button.name || format(index, scope.row, scope.column)}}
                </el-button>

              </template>
            </template>
            <template v-else-if="column.tag || column.tagColor">
              <el-tag v-if="column.tag" :type="column.tag(scope.row, scope.column)" size="small">
                {{format(index, scope.row, scope.column)}}
              </el-tag>
              <el-tag v-else :color="column.tagColor(scope.row, scope.column)" size="small">
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
              </el-tag>
            </template>
            <!--      特殊处理      -->
            <template v-else-if="column.type==='pop'">
              <div>
                <el-popover 
                  :trigger="column.trigger || 'click'" 
                  placement="top" 
                  :width="column.popWidth" 
                  :disabled=" typeof column.disabled === 'function'? column.disabled(scope.row, scope.column) : column.disabled "
                >
                  <slot :name="column.slotName || 'column-pop'" :row="scope.row"></slot>
                  <template #reference>
                    <el-button link type="primary"  :size="column.size ? column.size : 'small'">
                      {{ column.formatter ? format(index, scope.row, scope.column) : '点击查看' }}
                    </el-button>
                  </template>
                  
                </el-popover>
              </div>
            </template>

            <!-- 特殊处理 - 单元格特殊背景颜色 -->
            <template v-else-if="column.type === 'bgColor'">
              <div 
                :style="{
                  padding: '4px 0',
                  background: typeof column.color === 'function' ? column.color(scope.row) : column.color
                }"
              >
                {{format(index, scope.row, scope.column)}}
              </div>
            </template>

            <!-- 特殊处理 - html -->
            <template v-else-if="column.type === 'htmlPiece'">
              <div v-html="(format(index, scope.row, scope.column) && format(index, scope.row, scope.column).replaceAll('\n','<br/>')) || ''"></div>
            </template>

            <span v-else :style="{width: column.width, color: typeof column.color === 'function' ? column.color(scope.row) : column.color}" :title="format(index, scope.row, scope.column)">
              {{format(index, scope.row, scope.column)}}
            </span>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div style="display: flex; justify-content: center" v-if="showPagination">
      <el-pagination
        background
        :layout="pagination.layout || 'total, sizes, prev, pager, next, slot'"
        :total="pagination.total || 0"
        :current-page="pagination.pageIndex"
        :page-sizes="pagination.pageSizes || [10, 20, 30, 40, 50, 100]"
        :page-size="pagination.pageSize"
        :disabled="tableLoading"
        :size="pagination.size || 'small'"
        @current-change="currentPageChangeHandler"
        @size-change="sizeChangeHandler"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
export default {
  name: 'easy-table',
  props: {
    headerStyle: {
      type: Object,
    },
    selectedRow: {
      type: Number,
      default: 1,
    },
    pageTotal: {
      type: Number,
      default: 0,
    },
    pageSize: {
      type: Number,
      default: 10,
    },
    pagination: {
      type: Object,
      default: () => {
        return {
          pageIndex: 1,
          pageSize: 10,
        }
      }
    },
    showPagination: {
      type: Boolean,
      default: true,
    },
    border: {
      type: Boolean,
      default: false,
    },
    tableLoading: {
      type: Boolean,
      default: false,
    },
    highlightCurrentRow: {
      type: Boolean,
      default: true,
    },
    showLoadMore: {
      type: Boolean,
      default: false,
    },
    showIndex: Boolean,
    selection: {
      type: Boolean,
      default: false,
    },
    tableHeight: {
      type: [Number, String],
      // default: 585,
    },
    maxHeight: {
      type: [Number, String],
      // default: 585,
    },
    columns: Array,
    data: {
      type: Array,
      default: [],
    },
    tools: {
      type: Boolean,
      default: true,
    },
    showSummary: {
      type: Boolean,
      default: false,
    },
    sumText: {
      type: String,
      default: '合计',
    },
    align: {
      type: String,
      default: 'left',
    },
    headerAlign: {
      type: String,
      default: 'left',
    },
    primaryKey: {
      type: Array,
      default() {
        return [];
      },
    },
    needSummaryIndex: {
      type: Array,
      default() {
        return [];
      },
    },
    cellStyle: {
      type: Function
    },
    resetCurrentPage: {
      type: Boolean,
      default: false,
    },
    stripe:{
      type: Boolean,
      default: true,
    },
    indexOptions: {
      type: Object,
      default: () => {
        return {}
      },
    },
    spanMethod: {
      type: Function
    },
    reserveSelection: {
      type: Boolean,
      default: false,
    }
  },
  data() {
    return {
      hasMore: true,
      currentPage: 1,
      // pageSize: 10,
      allSelections: [],
    };
  },
  computed: {
    pageTableData() {
      // const results = [];
      // let i = (this.currentPage - 1) * this.pageSize;
      // let pageLimit = this.data.length;
      // if (this.currentPage * this.pageSize > this.data.length) {
      //   pageLimit = this.data.length;
      // } else {
      //   pageLimit = this.currentPage * this.pageSize;
      // }
      // for (i; i < pageLimit; i++) {
      //   results.push(this.data[i]);
      // }
      // return results;
      return this.data
    },
  },
  methods: {
    // 翻页让序号延续递增
    getIndex(index) {
      // 获取页码
      const page = this.pagination.pageIndex
      // 获取当前1页多少条
      const size = this.pagination.pageSize
      // console.log(page, size)
      // 当前页数 - 1 * 每页数据条数 + index + 1
      return (page - 1) * size + index + 1
    },

    selectChange(row) {
      // console.log(row);
      this.$emit('selectChange', row);
    },

    // 最后一行，按指定列做合计
    getSummaries (param) {
      const { columns, data } = param;
      const sums = [];
      let sumText = this.sumText;
      let needSummaryIndex = this.needSummaryIndex;
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = sumText;
          return;
        }
        if (needSummaryIndex.includes(index)) {
          const values = data.map(item => Number(item[column.property]));
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
            // sums[index] += ' 元';
          } else {
            sums[index] = '';
          }
        } else {
          sums[index] = '';
        }
      });
      return sums;
    },

    clearSelection () {
      this.$refs.table.clearSelection();
    },
    currentChangeHandler (currentRow, oldCurrentRow) {
      this.$emit('current-change', currentRow, oldCurrentRow);
    },
    currentPageChangeHandler (val) {
      this.$emit('page-current-change', val);
    },
    doLayout () {
      this.$refs.table.doLayout();
    },
    format (index, row, column) {
      if (this.columns[index].formatter) {
        return this.columns[index].formatter.call(this, row, column, row[column.property]);
      } else {
        return row[column.property];
      }
    },
    getAllSelections () {
      return this.allSelections;
    },
    rowClickHandler(row) {
      if (this.primaryKey.length) {
        this.currentRowIndex = this.primaryKey.map(key => {
          return row[key];
        }).join('-');
      } else {
        this.currentRowIndex = row.row_id;
        this.$emit('row-click',row)
      }
    },
    setCurrentRow(row) {
      this.$refs.table.setCurrentRow(row);
    },
    selectHandler (selection, row) {
      this.allSelections = selection;
      this.$emit('select', selection, row);
    },
    selectAllHandler (selection) {
      this.allSelections = selection;
      this.$emit('select-all', selection);
    },
    sizeChangeHandler (val) {
      this.$emit('page-size-change', val);
    }
  },
  watch: {
    tableHeight() {
      this.$refs.table.doLayout();
    },
  },
  mounted() {
    // console.log(this.selection);
  }
};
</script>
<style lang="scss" scoped>  
  .easy-table-container {
    width: 100%;
  }
  p {
    margin: 10px;
    font-size:24px;
    font-weight: bold;
  }
  .table-tools {
    padding: 18px 8px 12px;
    position: relative;
    .btn-right {
      float: right;
    }
  }
  .table-wrapper {
    padding: 0;
  }
  :deep(.el-table) {
    font-size: 14px;
    tr {
      height: 48px;
    }
    th {
      padding: 15px 0;
    }
    tr, td {
      font-weight: normal;
    }
    &::before{
      content: none !important;
    }
    .el-table__body-wrapper {
      /*滚动条整体部分*/
      &::-webkit-scrollbar {
        display: block;
        width: 10px;
        height: 10px;
        background-color: transparent;
      }
      /*滚动条里面的小方块*/
      &::-webkit-scrollbar-thumb {
        box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.05);
        -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.05);
        background-color: rgba(145, 148, 164, 0.15);
        border-radius: 10px;
      }
      /*滚动条里面的轨道*/
      &::-webkit-scrollbar-track {
        border-radius: 10px;
        box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.15);
        -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.15);
        background-color: #FFFFFF;
      }
    }
    // .el-table__row.current-row, .el-table__row--striped.current-row {
      // & > td {
        // background-color: #c5cfda !important;
      // }
    // }
  }
  .el-pagination {
    height: 38px;
    padding: 6px 0;
    text-align: center;
  }
</style>
